package com.android.infantschool.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.InfromBean;
import com.android.infantschool.event.NoticeEvent;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.mvp.presenter.ReadInfromPresenter;
import com.android.infantschool.model.mvp.presenter.ReadInfromPresenterImpl;
import com.android.infantschool.model.mvp.presenter.ReleaseInfromPresenter;
import com.android.infantschool.model.mvp.presenter.ReleaseInfromPresenterImpl;
import com.android.infantschool.model.mvp.view.ReadInfromView;
import com.android.infantschool.model.mvp.view.ReleaseInfromView;
import com.android.infantschool.ui.activity.ActInfromActivity;
import com.android.infantschool.ui.activity.CommonInfromActivity;
import com.android.infantschool.ui.activity.DetailsActivity;
import com.android.infantschool.ui.activity.VoteInfromActivity;
import com.android.infantschool.ui.adapter.InfromAdapter;
import com.android.infantschool.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\3 0003 13:08
 * @class describe 通知模块
 */
public class InfromFragment extends BaseFragment implements View.OnClickListener, InfromAdapter.OnLister, OnLoadMoreListener,
        OnRefreshListener, ReleaseInfromView, ReadInfromView {

    private RelativeLayout rlTitle;
    private TextView tvTitle;
    private ImageView imgTitle;
    private ImageView imgBack;
    private TextView tvSend;
    private View viewSend;
    private TextView tvRead;
    private View viewRead;
    private LinearLayout lyTitle;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;

    private InfromAdapter adapter;
    private PopupWindow popupWindow;

    private ReleaseInfromPresenter infromPresenter = null;
    private ReadInfromPresenter readInfromPresenter = null;

    private int TYPE_PHONE = 1;//1:我发布的,2:我收到的
    private int pageNum = 0;//总页数
    private int pageNow = 1;//当前请求的第几页
    private boolean isRefresh = false;//false:刷新  true:加载
    private ImageView imgNotice;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_inform, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        readInfromPresenter = new ReadInfromPresenterImpl(this);
        infromPresenter = new ReleaseInfromPresenterImpl(this);
        rlTitle = view.findViewById(R.id.title);
        tvTitle = view.findViewById(R.id.tv_title);
        imgBack = view.findViewById(R.id.img_back);
        imgBack.setImageResource(R.mipmap.icon_infrom_add);

        tvTitle.setText("通知");
        imgBack.setVisibility(View.GONE);

        imgTitle = view.findViewById(R.id.img_title);
        imgTitle.setOnClickListener(this);
        imgTitle.setVisibility(View.VISIBLE);

        tvSend = (TextView) view.findViewById(R.id.tv_send);
        tvSend.setOnClickListener(this);
        viewSend = (View) view.findViewById(R.id.view_send);
        tvRead = (TextView) view.findViewById(R.id.tv_read);
        tvRead.setOnClickListener(this);
        viewRead = (View) view.findViewById(R.id.view_read);
        lyTitle = (LinearLayout) view.findViewById(R.id.ly_title);
        lyTitle.setOnClickListener(this);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        refreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);
        imgNotice = (ImageView) view.findViewById(R.id.img_notice);
        imgNotice.setOnClickListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        adapter = new InfromAdapter(activity, this);
        recyclerView.setAdapter(adapter);

        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshHeader(new ClassicsHeader(activity));
        refreshLayout.setRefreshFooter(new ClassicsFooter(activity));
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        showSend();
    }

    @Override
    public void lister(int position, int type) {
        startActivity(DetailsActivity.newIntent(activity, adapter.list.get(position).getTitle(), adapter.list.get(position).getContent()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send:
                showSend();
                break;
            case R.id.tv_read:
                showRead();
                break;
            case R.id.img_title:
                if (popupWindow != null) {
                    if (popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    } else {
                        showPopWindow();
                    }
                } else {
                    showPopWindow();
                }
                break;
        }
    }

    private void showPopWindow() {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View vView = inflater.inflate(R.layout.dialog_infram, null);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(vView, imgTitle.getWidth() * 4, imgTitle.getHeight() * 5, true);
        }
        vView.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(CommonInfromActivity.newIntent(activity));
                popupWindow.dismiss();
            }
        });

        vView.findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(ActInfromActivity.newIntent(activity));
                popupWindow.dismiss();
            }
        });

        vView.findViewById(R.id.tv_3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(VoteInfromActivity.newIntent(activity));
                popupWindow.dismiss();
            }
        });
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(imgTitle, 20, 10, Gravity.RIGHT);
        }
    }

    private void showSend() {
        tvSend.setTextColor(0xFF007C70);
        tvRead.setTextColor(0xFF000000);
        viewRead.setVisibility(View.GONE);
        viewSend.setVisibility(View.VISIBLE);
        this.showLoading();
        adapter.clear();
        isRefresh = false;
        TYPE_PHONE = 1;
        pageNow = 1;
        getListRelease(pageNow);
    }

    private void showRead() {
        tvRead.setTextColor(0xFF007C70);
        tvSend.setTextColor(0xFF000000);
        viewSend.setVisibility(View.GONE);
        viewRead.setVisibility(View.VISIBLE);
        adapter.clear();
        isRefresh = false;
        TYPE_PHONE = 2;
        pageNow = 1;
        // TODO: 2019/8/10 获取收到的通知
        getListRead(pageNow);
    }

    private void getListRelease(int page) {
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("CountPerpage", "5");
        map.put("CurentPageIndex", String.valueOf(page));
        Log.e(TAG, "map:" + map.toString());
        infromPresenter.getReleaseInfrom(map);
    }

    private void getListRead(int page) {
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("isCheackedReceive", "true");
        map.put("CountPerpage", "5");
        map.put("CurentPageIndex", String.valueOf(page));
        Log.e(TAG, "map:" + map.toString());
        readInfromPresenter.getReadInfrom(map);
    }

    /**
     * 正在加载
     *
     * @param refreshLayout
     */
    @Override
    public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
        isRefresh = true;
        pageNow++;
        if (pageNow > pageNum) {//没有最新数据
            refreshLayout.finishLoadMore(true);
            refreshLayout.finishRefresh(true);
            return;
        }
        if (TYPE_PHONE == 1) {
            getListRelease(pageNow);
        } else if (TYPE_PHONE == 2) {
            getListRead(pageNow);
        }
    }

    /**
     * 正在刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
        isRefresh = false;
        pageNow = 1;
        if (TYPE_PHONE == 1) {
            getListRelease(pageNow);
        } else if (TYPE_PHONE == 2) {
            getListRead(pageNow);
        }
    }

    @Override
    public void errorReleaseInfrom(String error) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        ToastUtil.showShortToast(activity, "网络异常:" + error);
    }

    @Override
    public void successReleaseInfrom(BaseBean baseBean) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        InfromBean infromBean = (InfromBean) baseBean;
        if (infromBean.getCode() == 0) {
            pageNum = infromBean.getCount() / 5 + 1;//总条数
            if (isRefresh) {//加载
                adapter.addDataAll(infromBean.getData(), TYPE_PHONE);
            } else {//刷新
                adapter.setData(infromBean.getData(), TYPE_PHONE);
            }
            Log.e(TAG, "size:" + adapter.list.size());
        } else {
            ToastUtil.showShortToast(activity, "获取失败:" + infromBean.getMsg());
        }
    }

    @Override
    public void errorReadInfrom(String error) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        ToastUtil.showShortToast(activity, "网络异常:" + error);
    }

    @Override
    public void successReadInfrom(BaseBean baseBean) {
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        InfromBean infromBean = (InfromBean) baseBean;
        Log.e(TAG, "infromBean:" + infromBean.toString());
        if (infromBean.getCode() == 0) {
            pageNum = infromBean.getCount() / 5 + 1;//总条数
            if (isRefresh) {//加载
                // TODO: 2019/8/13 取消通知标红
                adapter.addDataAll(infromBean.getData(), TYPE_PHONE);
            } else {//刷新
                imgNotice.setVisibility(View.GONE);
                adapter.setData(infromBean.getData(), TYPE_PHONE);
            }
            Log.e(TAG, "size:" + adapter.list.size());
        } else {
            ToastUtil.showShortToast(activity, "获取失败:" + infromBean.getMsg());
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeMsg(NoticeEvent noticeEvent){
        imgNotice.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (popupWindow != null) {
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            } else {
                popupWindow = null;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (infromPresenter != null) {
            infromPresenter.onDestroy();
            infromPresenter = null;
        }
        if (readInfromPresenter != null) {
            readInfromPresenter.onDestroy();
            readInfromPresenter = null;
        }
    }

}